<template>
  <div>
    <Header />
    <div class="m_content">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="center-text">
          <p>进行您的帖子编辑</p>
        </div>
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title" />
        </el-form-item>

        <el-form-item label="帖子类型" prop="typePost">
          <el-select v-model="ruleForm.typePost" placeholder="请选择帖子类型">
            <el-option label="交换帖" value="exchange" />
            <el-option label="闲聊帖" value="chat" />
          </el-select>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <mavon-editor v-model="ruleForm.content" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">立即发布</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
// 导入全局变量
import { publishPost } from '@/api/post'
export default {
  data() {
    return {
      ruleForm: {
        id: '',
        title: '',
        content: '',
        typePost: '' // 初始化帖子类型字段
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          {
            min: 5,
            max: 100,
            message: '长度在 5 到 100 个字符',
            trigger: 'blur'
          }
        ],
        typePost: [
          { required: true, message: '请选择帖子类型', trigger: 'change' }
        ],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    console.log(localStorage.getItem('token'))

  },
  methods: {
    async submitForm(formName) {
      // 创建一个包含后端需要字段的对象
      const postData = {
        title: this.ruleForm.title,
        content: this.ruleForm.content,
        typePost: this.ruleForm.typePost // 添加类型字段
        // 可根据实际情况添加其他字段
      }

      try {
        // 发起 API 请求，并将新对象传递给 publishPost 方法
        const response = await publishPost(postData)
        // 处理成功响应，例如显示成功消息
        alert('发布成功:', response.data)

        // 在这里执行页面跳转
        this.$router.push('/exchangeBook/postCommunicate') // 替换 '/success-page' 为你想要跳转的页面路径

      } catch (error) {
        // 处理请求失败，例如显示错误消息
        alert('发布失败:', error.message)
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>
.m_content {
  margin: 0 auto;
}
.center-text {
  text-align: center;
}
</style>
